package com.xdxc.component.validation;

import com.xdxc.annotation.AnswerValidationRule;
import com.xdxc.model.dto.UserAnswerDto;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

import static com.xdxc.utils.convertToLongList.convertToLongList;

import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
@AnswerValidationRule(quType = 4)
@Component
public class ShortAnswerValidator implements AnswerValidator {
    // 配置参数
    private static final int MAX_ANSWER_LENGTH = 10000;
    private static final int MAX_LINE_BREAKS = 5;
    private static final Pattern INVALID_PATTERN = Pattern.compile(
            "[<>\"'`\\\\]|(script)|(http:|https:)",
            Pattern.CASE_INSENSITIVE
    );

    @Override
    public boolean validate(UserAnswerDto dto) {
        // 1. 基础空值检查
        if (dto == null || dto.getCheckId() == null || dto.getQuId() == null) {
            return false;
        }

        // 2. 内容存在性检查
        String answerText = dto.getAnswerText();
        if (StringUtils.isBlank(answerText)) {
            return false;
        }

        // 3. 长度限制检查
        if (answerText.length() > MAX_ANSWER_LENGTH) {
            return false;
        }

        // 4. 换行符限制（防止DOS攻击）
        if (countOccurrences(answerText, '\n') > MAX_LINE_BREAKS) {
            return false;
        }

        // 5. 危险字符/模式检查
//        if (INVALID_PATTERN.matcher(answerText).find()) {
//            System.out.println("换行符数量: " + countOccurrences(answerText, '\n'));
//
//            boolean hasInvalidChars = INVALID_PATTERN.matcher(answerText).find();
//            System.out.println("包含非法字符: " + hasInvalidChars);  System.out.println("MAX_LINE_BREAKS: " + MAX_LINE_BREAKS);
//            return false;
//        }

        // 6. 规范化检查（可选）
//        if (!answerText.equals(StringUtils.normalizeSpace(answerText.trim()))) {
//            return false;
//        }

        return true;
    }

    private int countOccurrences(String str, char ch) {
        return (int) str.chars().filter(c -> c == ch).count();
    }
}

